Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    isAdmin: false,
    adminKey: 'liang',
    cloud: null
  },

  onLoad() {
    this.initSharedCloud();
  },

  async initSharedCloud() {
    const cloud = new wx.cloud.Cloud({
      resourceAppid: 'wx3199c80279c7b8c3',
      resourceEnv: 'education-6gwexwp8488514df'
    });
    
    try {
      await cloud.init();
      this.setData({ cloud });
    } catch (err) {
      console.error('初始化云环境失败：', err);
      wx.showToast({
        title: '系统初始化失败',
        icon: 'error'
      });
    }
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  onConfirmPasswordInput(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  toggleAdmin() {
    this.setData({
      isAdmin: !this.data.isAdmin
    });
  },

  onAdminKeyInput(e) {
    this.setData({
      adminKey: e.detail.value
    });
  },

  async handleRegister() {
    const { username, password, confirmPassword, isAdmin, adminKey, cloud } = this.data;

    if (!username || !password || !confirmPassword) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (isAdmin && !adminKey) {
      wx.showToast({
        title: '请输入管理员密钥',
        icon: 'none'
      });
      return;
    }

    if (isAdmin && adminKey !== 'admin123') {
      wx.showToast({
        title: '管理员密钥错误',
        icon: 'none'
      });
      return;
    }

    if (password !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      });
      return;
    }

    try {
      const db = cloud.database();
      
      // 检查用户名是否已存在
      const { data } = await db.collection('users')
        .where({ username })
        .get();

      if (data.length > 0) {
        wx.showToast({
          title: '用户名已存在',
          icon: 'none'
        });
        return;
      }

      // 创建新用户
      await db.collection('users').add({
        data: {
          username,
          password,
          role: isAdmin ? 'admin' : 'user',
          createTime: db.serverDate()
        }
      });

      wx.showToast({
        title: '注册成功',
        icon: 'success'
      });

      // 延迟跳转到登录页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);

    } catch (err) {
      console.error('注册失败：', err);
      wx.showToast({
        title: '注册失败，请重试',
        icon: 'error'
      });
    }
  },

  goToLogin() {
    wx.navigateBack();
  }
}); 